package com.alibaba.cloudalibabaserver.service;


import com.alibaba.cloudalibabaserver.bean.Order;
import com.alibaba.cloudalibabaserver.bean.OrderDetail;
import com.alibaba.cloudalibabaserver.bean.OrderItem;
import com.alibaba.cloudalibabaserver.repository.OrderItemRepository;
import com.alibaba.cloudalibabaserver.repository.OrderRepository;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
@AllArgsConstructor
public class OrderService {


    private final OrderRepository orderRepository;
    private final OrderItemRepository orderItemRepository;

    /**
     * 创建订单 - 测试分库分表插入
     */
    @Transactional
    public OrderItem createOrder(Integer i,Long userId, Double amount) {
        Order order = new Order();
        // 注意：主键由Sharding-JDBC的雪花算法自动生成
        // 但在JPA中需要手动设置，或者使用数据库自增（不推荐在分片场景使用）
        order.setUserId(userId);
        order.setOrderAmount(amount);
        order.setOrderStatus(1);
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        Order save = orderRepository.save(order);
        OrderItem entity = new OrderItem();
        entity.setOrderId(Long.valueOf(i));
        entity.setUserId(userId);
        entity.setOrderAmount(amount);
        entity.setOrderStatus(1);
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        orderItemRepository.save(entity);
        return entity;
    }

    /**
     * 批量创建订单
     */
    @Transactional
    public void batchCreateOrders(int count) {
        Random random = new Random();
        for (int i = 0; i < count; i++) {
            Long userId = (long) random.nextInt(100);
            Double amount = 100 + random.nextDouble() * 900;
            createOrder(i,userId, amount);
        }
    }


    /**
     * 根据用户ID查询订单
     */
    public List<Order> getOrdersByUserId(Long userId) {
        return orderRepository.findByUserId(userId);
    }

    /**
     * 根据订单ID查询
     */
    public Order getOrderById(Long orderId) {
        return orderRepository.findById(orderId).orElse(null);
    }

    /**
     * 查询所有订单（会查询所有分片）
     */
    public List<Order> getAllOrders() {
        return orderRepository.findAll();
    }

    /**
     * 范围查询示例
     */
    public List<Order> getOrdersByUserIdRange(Long startUserId, Long endUserId) {
        return orderRepository.findByUserIdBetween(startUserId, endUserId);
    }

    /**
     * 范围查询示例
     */
    public List<OrderDetail> getOrdersByUserIdRange(Long userId) {
        return orderItemRepository.selectOrderDetailByUserId(userId);
    }
}
